package dryven.codegen.asm;

import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

import dryven.codegen.asm.typeinfo.TypeInfo;

public class FieldInstance implements ReadableSymbol, Assignable {

	private FieldDefinition _fieldDef;
	private MethodBuilder _builder;
	private SubOperationListener _parent;
	
	public FieldInstance(FieldDefinition fieldDef, MethodBuilder builder, SubOperationListener parent) {
		super();
		_fieldDef = fieldDef;
		_builder = builder;
		_parent = parent;
	}

	@Override
	public TempValue read() {
		_parent.preOperation(0);
		_builder.getMethodVisitor().visitFieldInsn(Opcodes.GETFIELD,_fieldDef.getClassType().getInternalClassName(), _fieldDef.getName(), _fieldDef.getType().getTypeDescriptor());
		_parent.postOperation();
		return new TempValue(getTypeInfo(), _builder);
	}

	@Override
	public TypeInfo getTypeInfo() {
		return _fieldDef.getType();
	}

	@Override
	public void assign(TempValue e) {
		e.checkValid();
		_parent.preOperation(1);
		MethodVisitor mv = _builder.getMethodVisitor();
		mv.visitInsn(Opcodes.SWAP);
		mv.visitFieldInsn(Opcodes.PUTFIELD,_fieldDef.getClassType().getInternalClassName(), _fieldDef.getName(), _fieldDef.getType().getTypeDescriptor());
		_parent.postOperation();
		e.pop();
	}

}
